//
//  HomePageTableViewController.m
//  PetTown
//
//  Created by lanou3g on 15/5/28.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "HomePageTableViewController.h"
#import "AppDelegate.h"
#import "AFNetMonitor.h"
@interface HomePageTableViewController ()
{
    ChoicenessCell *cell;
    MBProgressHUD * HUD;
}
@end

@implementation HomePageTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.allDataArray = [[NSMutableArray alloc] init];
    _a = 1;
    //下拉刷新
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //上啦刷新
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    //抽屉
    [self chouti];
    
    
    //设置背景图片
    self.tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"backImg.png"]];


    
    NSArray * rrr = [NSArray arrayWithObjects:@"精品",@"最新", nil];
    self.change = [[UISegmentedControl alloc] initWithItems:rrr];
    _change.selectedSegmentIndex = 0;
    _change.frame = CGRectMake(0, 15, 100, 25);
    
    [_change addTarget:self action:@selector(changeView:) forControlEvents:UIControlEventValueChanged];

    self.navigationItem.titleView = _change;
    


    
#pragma mark----数据解析

    [self JSOn];
    //设置navigation
    AppDelegate * app = (AppDelegate * )[UIApplication sharedApplication].delegate;
    app.NC = self.navigationController;
    
    
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}



-(void)alertView:(NSString *)message
{
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"通知" message:message delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
    [alertView show];
}

#pragma mark----抽屉
- (void)chouti{
    UIButton * leftBu = [UIButton buttonWithType:(UIButtonTypeSystem)];
    leftBu.frame = CGRectMake(0, 0, 25, 25);
    [leftBu setBackgroundImage:[UIImage imageNamed:@"DrawerPage.png"] forState:UIControlStateNormal];
    [leftBu addTarget:self action:@selector(presentLeftMenuViewController:) forControlEvents:UIControlEventTouchDown];
    UIBarButtonItem * leftBu1 = [[UIBarButtonItem alloc] initWithCustomView:leftBu];
    self.navigationItem.leftBarButtonItem = leftBu1;
}

//下拉刷新

- (void)headerRereshing{
    
    [self.tableView headerEndRefreshing];
}
//上拉刷新
-(void)footerRereshing{
    _a++;
    if (_change.selectedSegmentIndex == 0) {
        _uu = [NSString stringWithFormat:ChoicenessPageAPI,[NSString stringWithFormat:@"%d",_a]];
    }else if (_change.selectedSegmentIndex == 1){
        _uu = [NSString stringWithFormat:NewestPageAPI,[NSString stringWithFormat:@"%d",_a]];
    }
    [self JSOn];
    [self.tableView footerEndRefreshing];
}
- (void)shiyan:(UIBarButtonItem *)bb{
    MengwTableViewController * aa = [[MengwTableViewController alloc] init];
    [self.navigationController pushViewController:aa animated:YES];
}
- (void)changeView:(UISegmentedControl *)se{
    switch (se.selectedSegmentIndex) {
        case 0:{
            _a = 1;
            [_allDataArray removeAllObjects];
            _uu = [NSString stringWithFormat:ChoicenessPageAPI,[NSString stringWithFormat:@"%d",_a]];
            [self JSOn];
        }
            break;
        case 1:{
            _a = 1;
            [_allDataArray removeAllObjects];
            _uu = [NSString stringWithFormat:NewestPageAPI,[NSString stringWithFormat:@"%d",_a]];
            [self JSOn];
        }
            break;
            
        default:
            break;
    }
}
#pragma mark----数据解析
- (void)JSOn{
    HUD = [[MBProgressHUD alloc] initWithView:self.tableView];
    [self.tableView addSubview:HUD];
    HUD.labelText = @"正在加载";
    [HUD show:YES];
    

    if (!_uu) {
        _uu = [NSString stringWithFormat:ChoicenessPageAPI,[NSString stringWithFormat:@"%d",_a]];
    }

  
    
    
    NSURL * url = [NSURL URLWithString:_uu];
    
    NSURLRequest * request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60.0];
    __weak HomePageTableViewController * HPTVC = self;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data == nil)
        {
            return;
        }
        
        NSMutableDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableDictionary * dic1 = dic[@"data"];
        NSArray * array = dic1[@"list"];
        for (NSDictionary * modelDic in array) {
            HomePage * homePage = [[HomePage alloc] init];
            [homePage setValuesForKeysWithDictionary:modelDic];
            [HPTVC.allDataArray addObject:homePage];
        }
        [self.tableView reloadData];
    }];
    CATransition * animation = [CATransition animation];
    animation.duration = 0.5;
    animation.type = @"cube";
    animation.subtype = kCATransitionFromRight;
    [self.tableView.layer addAnimation:animation forKey:@"过度动画"];
    [AFNetMonitor sharedClient];

}


#pragma mark----抽屉
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}


//点击表尾视图推出详情页面
- (void)pushHomePageNewVC:(UIButton *)button{
    HomePageNewTableViewController * homePageNewTVC = [[HomePageNewTableViewController alloc] init];
    [self.navigationController pushViewController:homePageNewTVC animated:YES];
}
- (void)clickRadio:(UIBarButtonItem *)BI{
    RadioPageController * radioPageVC = [[RadioPageController alloc] init];
    [self.navigationController pushViewController:radioPageVC animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    //清除缓存
    SDImageCache * sdI = [SDImageCache sharedImageCache];
    [sdI clearDisk];
    [sdI clearMemory];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    if (_allDataArray.count != 0) {
        return _allDataArray.count;
    }else{
        return 10;
    }
}
//cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_allDataArray.count != 0) {
        HomePage * homePage = _allDataArray[indexPath.row];
        CGFloat a = self.tableView.frame.size.width * [homePage.picheight floatValue] / [homePage.picwidth floatValue] + 275;
        return a;
    }else{
        return 100;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {


    cell = [[ChoicenessCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"newPagecell1"];
    if (!cell) {
        cell = [[ChoicenessCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"mycell"];
    }
    if (_allDataArray.count != 0) {
        HomePage * hh = _allDataArray[indexPath.row];
        cell.homePage = hh;
        if (hh.comments.count != 0) {
            self.ReviewerArray = [[NSMutableArray alloc] init];
            for (NSDictionary * dd in hh.comments) {
                Reviewer * rr = [[Reviewer alloc] init];
                [rr setValuesForKeysWithDictionary:dd];
                [_ReviewerArray addObject:rr];
                cell.reviewer = _ReviewerArray[0];
            }
            
        }
        if (hh.comments.count == 0){
            UILabel * ll = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 80)];
            ll.text = @"暂无评论";
            ll.textAlignment = NSTextAlignmentCenter;
            [cell.pl_view addSubview:ll];
        }
        
        //HUD = nil;
        [MBProgressHUD hideHUDForView:self.tableView animated:YES];
    }



    
    return cell;
}
//点击cell弹出详情
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    HomePageNewTableViewController * homePageNewTVC = [[HomePageNewTableViewController alloc] init];
    HomePage * hh = _allDataArray[indexPath.row];
    homePageNewTVC.homePage = hh;
    if (_allDataArray.count != 0) {
        [self.navigationController pushViewController:homePageNewTVC animated:YES];
    }
    
    
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
